<template>
  <view class="baseForm">
    <!-- 搜索&扫码 -->
    <!-- <view class="upload-scan">
			<u-search
				v-model="planName"
				shape="round"
				bgColor="#fff"
				:show-action="true"
				actionText="搜索"
				:animation="true"
				class="search"
				placeholder="请输入任务编号或名称"
				@search="searchList"
				@clear="searchList"
				@custom="searchList"></u-search>
			<u-icon
				name="scan"
				size="27px"
				:bold="false"
				@click="scanHandle"></u-icon>
		</view> -->

    <view
      class="flex justify-between"
      style="padding: 0 10px; margin-bottom: 1px; padding-top: 1px">
      <view @click="showPositionPicker" class="flex input-box-position">
        <u--input
          v-model="position"
          prefixIcon="search"
          border="none"
          placeholder="请选择位置"
          readonly
          class="input-self"></u--input>
        <image
          @click.stop="clearInfo()"
          v-show="position"
          src="@/static/image/delete.png" />
      </view>
    </view>

    <!-- tab-bar切换 -->
    <view class="tab-bar">
      <u-tabs
        :current="activeTab"
        :list="tabList"
        :scrollable="false"
        :activeStyle="{
          color: '#000',
          fontWeight: 'bold',
          transform: 'scale(1.04)',
        }"
        lineWidth="50px"
        lineHeight="2px"
        lineColor="#007aff"
        @change="changeTab"></u-tabs>
    </view>

    <!-- 当前作业 -->
    <view v-if="activeTab === 0" class="activeHeight">
      <!-- 列表 -->
      <u-list
        ref="tableScroll"
        @scrolltolower="scrolltolower"
        class="list"
        v-if="total"
        :height="listHeight"
        :lowerThreshold="100"
        :pagingEnabled="true">
        <u-list-item
          v-for="(item, index) in tableList"
          :key="item.id"
          @click="jump('/eam/equ/routingInspection/history', item.id)">
          <view class="card">
            <view class="flex record-title">
              <text class="line1">
                {{ item.taskName }}
              </text>
              <text v-if="item.taskStatus == 0" class="orange-color">
                待巡检
              </text>
              <text v-if="item.taskStatus == 1">巡检中</text>
              <text v-if="item.taskStatus == 2" class="grey-color">已完成</text>
            </view>
            <view class="flex flex-col justify-between flex-1 h-full">
              <view class="record-content">
                <view class="record-item">
                  <!-- <text>{{ item.taskNo }}</text> -->
                  <!--  <view class="flex">
                    <text>未检({{ item.notInspectedNumber || 0 }})</text>
                    <text
                      v-if="item.exceptionNumber"
                      class="red-color u-m-l-15">
                      异常({{ item.exceptionNumber || 0 }})
                    </text>
                  </view> -->
                  <view class="flex" style="justify-content: space-around">
                    <u-text
                      v-if="item?.inspectTotalNumber != null"
                      :text="`应检数(${item?.inspectTotalNumber || 0})`"
                      :size="14"
                      style="display: inline; flex: none; width: auto"></u-text>

                    <u-text
                      v-if="item?.notInspectedNumber != null"
                      :text="`未检(${item?.notInspectedNumber || 0})`"
                      :size="14"
                      style="
                        display: inline;
                        flex: none;
                        width: auto;
                        margin-left: 5px;
                      "></u-text>
                    <u-text
                      v-if="item?.notInspectedNumber != null"
                      :text="`已检数(${
                        Number(item?.inspectTotalNumber) -
                        Number(item?.notInspectedNumber)
                      })`"
                      :size="14"
                      style="
                        display: inline;
                        flex: none;
                        width: auto;
                        margin-left: 5px;
                      "></u-text>
                    <u-text
                      v-if="item?.exceptionNumber"
                      :text="`异常(${item?.exceptionNumber})`"
                      :size="14"
                      color="red"
                      :bold="true"
                      style="
                        display: inline;
                        flex: none;
                        width: auto;
                        margin-left: 5px;
                      "></u-text>
                  </view>
                </view>
                <view class="record-item">
                  <text>计划执行时间</text>
                  <text>
                    {{ getSecondTime(item?.planExecuteTime) || "" }}
                  </text>
                </view>
                <view class="record-item" v-if="item?.inspectionRouteName">
                  <text>巡检路线</text>
                  <text>
                    {{ item?.inspectionRouteName || "" }}
                  </text>
                </view>
              </view>
            </view>
            <!-- <view class="record-footer">
							<text class="canel font-14 mr-3" v-if="item.unresolvedItemCount" @click="jump('/ssm/unqualifiedList', item.id)">不合格:{{ item.unresolvedItemCount }}</text>
							<button v-show="item.taskStage === 1" class="record-btn reach" @click="selectTaskOpen(item, index)">开始</button>
							<button v-show="item.taskStage === 2" class="record-btn reach" @click="selectTaskOpen(item, index)">完成</button>
							<button class="record-btn reach" @click="jump('/ssm/check', item.id)">检 查</button>
							<button class="record-btn complete" @click="jump('/ssm/history', item.id)">历 史</button>
						</view> -->
          </view>
        </u-list-item>
      </u-list>
      <view class="flex justify-center" v-show="tableLoading">
        <u-loading-icon color="#000a7b"></u-loading-icon>
      </view>
      <!-- 空数据 -->
      <view v-show="tableList.length === 0 && !tableLoading">
        <u-empty
          mode="list"
          icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
      </view>
    </view>

    <!-- 历史作业 -->
    <view v-else class="activeHeight">
      <!-- 列表 -->
      <u-list
        @scrolltolower="finishScrolltolower"
        class="list"
        v-if="finishTotal"
        :height="listHeight"
        lowerThreshold="50px">
        <u-list-item
          v-for="(item, index) in finishTableList"
          :key="item.id"
          @click="jump('/eam/equ/routingInspection/history', item.id)">
          <!-- <view class="card">
						<view class="flex justify-center">
							<text class="record-title">{{ item.dangerTaskNo }} - {{ item.dangerTaskName }}</text>
						</view>
						<view class="flex flex-col justify-between flex-1 h-full">
							<view class="record-content">
								<view class="record-item">
									<text>项目负责部门</text>
									<text>{{ item?.responsibleDeptName || '' }}</text>
								</view>
								<view class="record-item">
									<text>项目负责人</text>
									<text>{{ item?.responsiblePerson || '' }}</text>
								</view>
								<view class="record-item">
									<text>施工部门/单位</text>
									<text>{{ item?.constructionDeptName || '' }}</text>
								</view>
								<view class="record-item">
									<text>现场负责人</text>
									<text>{{ item?.constructionDeptPerson || '' }}</text>
								</view>
								<view class="record-item">
									<text>作业地点</text>
									<text>{{ item?.taskLocationName || '' }}</text>
								</view>
								<view class="record-item">
									<text>作业时间</text>
									<text class="font-13">{{ getSecondTime(item?.planStartTime) }} 至 {{ getSecondTime(item?.planEndTime) }}</text>
								</view>
								<view class="record-item">
									<text>最近检查时间</text>
									<text>{{ item?.lastUpdateTime }}</text>
								</view>
							</view>
						</view>
						<view class="record-footer">
							<button class="record-btn complete" @click="jump('/ssm/history', item.id)">检查记录</button>
						</view>
					</view> -->
          <view class="card">
            <view class="flex record-title">
              <text class="line1">
                {{ item.taskName }}
              </text>
              <text v-if="item.taskStatus == 0" class="orange-color">
                待巡检
              </text>
              <text v-if="item.taskStatus == 1">巡检中</text>
              <text v-if="item.taskStatus == 2" class="grey-color">已完成</text>
            </view>
            <view class="flex flex-col justify-between flex-1 h-full">
              <view class="record-content">
                <view class="record-item">
                  <!--   <text>{{ item.taskNo }}</text> -->
                  <!-- <view class="flex">
										<text>未检({{item.notInspectedNumber || 0}})</text>
										<text v-if="item.exceptionNumber" class="red-color u-m-l-15">异常({{item.exceptionNumber || 0}})</text>
									</view> -->
                  <view class="flex" style="justify-content: space-around">
                    <u-text
                      v-if="item?.inspectTotalNumber != null"
                      :text="`应检数(${item?.inspectTotalNumber || 0})`"
                      :size="14"
                      style="display: inline; flex: none; width: auto"></u-text>

                    <u-text
                      v-if="item?.notInspectedNumber != null"
                      :text="`未检(${item?.notInspectedNumber || 0})`"
                      :size="14"
                      style="
                        display: inline;
                        flex: none;
                        width: auto;
                        margin-left: 5px;
                      "></u-text>
                    <u-text
                      v-if="item?.notInspectedNumber != null"
                      :text="`已检数(${
                        Number(item?.inspectTotalNumber) -
                        Number(item?.notInspectedNumber)
                      })`"
                      :size="14"
                      style="
                        display: inline;
                        flex: none;
                        width: auto;
                        margin-left: 5px;
                      "></u-text>
                    <u-text
                      v-if="item?.exceptionNumber"
                      :text="`异常(${item?.exceptionNumber})`"
                      :size="14"
                      color="red"
                      :bold="true"
                      style="
                        display: inline;
                        flex: none;
                        width: auto;
                        margin-left: 5px;
                      "></u-text>
                  </view>
                </view>
                <view class="record-item">
                  <text>计划执行时间</text>
                  <text>
                    {{ getSecondTime(item?.planExecuteTime) || "" }}
                  </text>
                </view>
                <view class="record-item" v-if="item?.inspectionRouteName">
                  <text>巡检路线</text>
                  <text>
                    {{ item?.inspectionRouteName || "" }}
                  </text>
                </view>
              </view>
            </view>
            <!-- <view class="record-footer">
							<text class="canel font-14 mr-3" v-if="item.unresolvedItemCount" @click="jump('/ssm/unqualifiedList', item.id)">不合格:{{ item.unresolvedItemCount }}</text>
							<button v-show="item.taskStage === 1" class="record-btn reach" @click="selectTaskOpen(item, index)">开始</button>
							<button v-show="item.taskStage === 2" class="record-btn reach" @click="selectTaskOpen(item, index)">完成</button>
							<button class="record-btn reach" @click="jump('/ssm/check', item.id)">检 查</button>
							<button class="record-btn complete" @click="jump('/ssm/history', item.id)">历 史</button>
						</view> -->
          </view>
        </u-list-item>
      </u-list>
      <view class="flex justify-center" v-show="finishTableLoading">
        <u-loading-icon color="#000a7b"></u-loading-icon>
      </view>
      <!-- 空数据 -->
      <view v-show="finishTableList.length === 0 && !finishTableLoading">
        <u-empty
          mode="list"
          icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
      </view>
    </view>

    <u-modal
      :show="showImport"
      ref="uModal"
      :content="`当前作业编号为${selectTask?.dangerTaskNo ?? ''}, 请确认是否${
        selectTask.taskStage === 1 ? '开始' : '完成'
      }作业？`"
      confirmText="确认"
      showCancelButton
      @cancel="cancelImport"
      @confirm="confirmImport"></u-modal>

    <!-- 树形选择器 -->
    <ba-tree-picker
      ref="positionPicker"
      :multiple="false"
      @select-change="positionChange"
      title="位置"
      :selectedData="showPositionValue"
      :localdata="positionList"
      valueKey="id"
      textKey="locationName"
      childrenKey="nodes" />
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, watch, reactive } from "vue";
import {
  onShow,
  onPullDownRefresh,
  onLoad,
  onBackPress,
} from "@dcloudio/uni-app";
import { http } from "@/utils/http";
import { PageResult, TabInfo } from "@/types/type";
import { getSecondTime } from "@/utils/common";
import { useDictionaryStore } from "@/stores/useDictionaryStore";
import { toScanCode } from "@/components/hs-scancode/scan.js";
// import mumuGetQrcode from '@/uni_modules/mumu-getQrcode/components/mumu-getQrcode/mumu-getQrcode.vue';
import { useEamStore } from "@/stores/useEamStore";

// 监听返回按钮事件
onBackPress((option) => {
  if (option.from === "backbutton") {
    uni.switchTab({
      url: "/pages/index/index",
    });
  }
  return true;
});

function qrcodeSucess(data) {
  uni.showModal({
    title: "成功",
    content: data,
    success: () => {
      // uni.navigateBack({})
    },
  });
}
function qrcodeError(err) {
  console.log(err);
  uni.showModal({
    title: "摄像头授权失败",
    content: "摄像头授权失败，请检测当前浏览器是否有摄像头权限。",
    success: () => {
      // uni.navigateBack({})
    },
  });
}

// 待完成数据
const tableList = ref([]);
const tableLoading = ref(false);
const current = ref(0);
const totalPage = ref(0);
const total = ref(0);

// 已完成数据
const finishTableList = ref([]);
const finishTableLoading = ref(false);
const finishCurrent = ref(0);
const finishTotalPage = ref(0);
const finishTotal = ref(0);

//列表高度
const listHeight = ref("");

// 已完成列表获取
async function finishLoadmore(type?: string) {
  try {
    finishCurrent.value += 1;
    finishTableLoading.value = true;
    const result: PageResult<any> = await http({
      method: "POST",
      url: "/eam/equRouteInspectionTask/queryMyList",
      data: {
        current: finishCurrent.value,
        size: 20,
        data: {
          finishStatus: 1,
          taskName: planName.value,
          locationId: positionId.value,
        },
      },
    }).finally(() => {
      finishTableLoading.value = false;
    });
    const list = result.data;
    for (let i = 0; i < list.length; i++) {
      finishTableList.value.push(list[i]);
    }
    finishTotalPage.value = result.page;
    finishTotal.value = result.total;
    type === "refresh" && uni.stopPullDownRefresh();
  } catch (e) {
    console.log(e);
  }
}

onLoad(() => {
  // #ifdef H5
  listHeight.value = "calc(100vh - 88px - 38px)";
  // #endif

  // #ifdef APP-PLUS
  listHeight.value = "calc(100vh - 48px - 38px)";
  // #endif
  // loadmore();
});

onPullDownRefresh(() => {
  searchList();
});

onShow(() => {
  searchList();
});

async function loadmore(type?: string) {
  try {
    current.value += 1;
    tableLoading.value = true;
    const result: PageResult<any> = await http({
      method: "POST",
      url: "/eam/equRouteInspectionTask/queryMyList",
      data: {
        current: current.value,
        size: 20,
        data: {
          finishStatus: 0,
          taskName: planName.value,
          locationId: positionId.value,
        },
      },
    }).finally(() => {
      tableLoading.value = false;
    });

    const list = result.data;
    for (let i = 0; i < list.length; i++) {
      tableList.value.push(list[i]);
    }
    totalPage.value = result.page;
    total.value = result.total;
    type === "refresh" && uni.stopPullDownRefresh();
  } catch (e) {
    console.log(e);
  }
}
const scrolltolower = () => {
  // alert(current.value)
  totalPage.value > current.value && loadmore();
};

const finishScrolltolower = () => {
  finishTotalPage.value > finishCurrent.value && finishLoadmore();
};
const activeTab = ref(0);
const tabList = computed(() => [
  { name: `未完成(${total.value})` },
  { name: `已完成(${finishTotal.value})` },
]);
function changeTab(val: TabInfo) {
  activeTab.value = val.index;
  if (val.index === 0 && !tableList.value.length) {
    loadmore();
  } else if (val.index === 1 && !finishTableList.value.length) {
    finishLoadmore();
  }
}

// 选择作业
const selectTask = ref({});
const showImport = ref(false);
function selectTaskOpen(row, index) {
  showImport.value = true;
  selectTask.value = row;
}

// 取消选择
function cancelImport() {
  showImport.value = false;
  selectTask.value = {};
}

function changeStatus() {
  return new Promise(async (resolve, reject) => {
    const res = await http({
      method: "POST",
      url:
        selectTask.value.taskStage === 1
          ? "/ssm/dangerTaskSupervise/startTask"
          : "/ssm/dangerTaskSupervise/endTask",
      data: {
        id: selectTask.value.id,
      },
    });
    resolve(res);
  });
}
// 追加加工单
async function confirmImport() {
  showImport.value = false;
  const { code } = await changeStatus();
  if (code === 200) {
    uni.showToast({
      title: "操作成功",
    });
    if (activeTab.value === 0) {
      current.value = 0;
      tableList.value = [];
      loadmore();
    } else {
      finishCurrent.value = 0;
      finishTableList.value = [];
      finishLoadmore();
    }
  } else {
    uni.showToast({
      title: "操作失败",
    });
  }
}

// H5端扫码调用
const showMumuQrcode = ref(false);

// 点击扫码
const planName = ref("");
// function openScan() {
// 	/* #ifdef H5 */
// 	uni.showToast({
// 		icon: "none",
// 		title: "请到安卓设备进行扫码",
// 	});
// 	showMumuQrcode.value = true;
// 	/* #endif */
// 	// 只允许通过相机扫码
// 	uni.scanCode({
// 		scanType: ["barCode", "qrCode"],
// 		onlyFromCamera: true,
// 		success: function (res) {
// 			planName.value = JSON.stringify(res.result);
// 			searchList();
// 			console.log("条码类型：" + res.scanType);
// 			console.log("条码内容：" + res.result);
// 		},
// 	});
// }

function scanHandle() {
  toScanCode({
    onlyFromCamera: true, // 只允许通过相机扫码
  })
    .then((res) => {
      uni.showToast({
        icon: "success",
        title: "扫码成功",
      });
      planName.value = res;
      searchList();
    })
    .catch((e) => {
      uni.showToast({
        icon: "error",
        title: e,
      });
    });
}

// 列表搜索
function searchList() {
  // 当前作业
  current.value = 0;
  tableList.value = [];
  loadmore("refresh");
  // 历史作业
  finishCurrent.value = 0;
  finishTableList.value = [];
  finishLoadmore("refresh");
}

// 网页跳转
function jump(item, id) {
  uni.navigateTo({
    url: `/pages${item}?id=${id}`,
    fail: () => {
      uni.showToast({
        title: "敬请期待",
        icon: "error",
      });
    },
  });
}

function jump1(item) {
  uni.navigateTo({
    url: `/pages${item}`,
    fail: () => {
      uni.showToast({
        title: "敬请期待",
        icon: "error",
      });
    },
  });
}

// 新加的位置与设备选择功能如下

// 选择位置信息
const selectedPosition = computed(() =>
  JSON.parse(useEamStore().selectedPosition)
);

// 显示选择器
const positionId = ref("");
const position = ref("");
const positionPicker = ref();
function showPositionPicker() {
  positionPicker.value._reTreeList();
  positionPicker.value._show();
}
//监听选择（ids为数组）
const showPositionValue = ref([]);
function positionChange(ids, names) {
  console.log("ids", ids, names);
  positionId.value = ids[0] ?? "";
  position.value = names ?? "";
  showPositionValue.value = ids[0] ? [ids[0]] : [];
  useEamStore().setSelectedPosition({
    positionId: ids[0] ?? "",
    positionName: names ?? "",
  });
  if (ids.length) {
    searchList();
  }
}

// 清空数据
function clearInfo() {
  positionId.value = "";
  position.value = "";
  useEamStore().setSelectedPosition({});
  showPositionValue.value = [];
  if (positionPicker.value?._reTreeList) {
    positionPicker.value._reTreeList();
  }
  searchList();
}
// 获取位置列表
const positionList = ref();
async function getPositionList() {
  const { data } = await http({
    method: "POST",
    url: `/eam/locationInfo/getTree`,
    data: {},
  });
  positionList.value = data;
}
onLoad(() => {
  useEamStore().setSelectedPosition({});
  getPositionList();
});
</script>

<style lang="scss" scoped>
uni-page-body {
  height: 100%;
  background-color: $primary-bg-color;
}
.search {
  :deep(.u-search__content) {
    box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
  }
}
.baseForm {
  background-color: $primary-bg-color;
  .tab-bar {
    padding: 0 40px;
  }
  .upload-scan {
    padding: $uni-page-padding;
    padding-top: 5px;
    padding-bottom: 5px;
    display: flex;
    align-items: center;
    // box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
    .u-icon {
      margin-left: 8px;
    }
  }
  .u-line {
    padding: 10px 0;
  }
}
.list {
  .card {
    margin: $uni-page-padding;
    margin-top: 5px;
    margin-bottom: 7px;
    border-radius: 7px;
    padding: 12px 10px 6px 10px;
    transition: all 300ms ease;
    box-shadow: 0 1px 5px rgba(19, 11, 236, 0.13);
    background-color: #fff;
    .card-flex {
      display: flex;
      align-items: flex-start;
    }
    .right {
      flex: 1;
    }
    .title {
      font-size: 14px;
      line-height: 40px;
      height: 40px;
      margin-top: 8px;
      font-weight: bold;
      color: #101010;
      border-top: 1px solid #e5ebff;
    }
    .uni-btn {
      float: right;
      font-size: 12px;
      height: 24px;
      line-height: 24px;
      padding: 0 15px;
      margin-top: 7px;
      font-weight: 400;
    }
    .des {
      font-size: 12px;
      line-height: 20px;
      // height: 20px;
      margin-bottom: 3px;
    }
    .left {
      // flex: 1;
      flex-basis: calc(50% + 10px);
    }
  }
}

.record-title {
  display: flex;
  justify-content: space-between;
  margin: 3px 0 2px 0;
  color: $primary-color;
  uni-text:nth-child(1) {
    font-weight: bold;
    font-size: 16px;
  }
  uni-text:nth-child(2) {
    font-size: 14px;
    min-width: 60px;
    text-align: right;
  }
}
.record-footer {
  // height: 30px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 10px 0 17px;
  .record-btn {
    height: 30px;
    outline: none;
    border: none;
    line-height: 30px;
    border-radius: 6px;
    font-size: 14px;
    margin: 0px;
    margin-left: 10px;
    padding: 0 12px;
  }
  .reach {
    background-color: $primary-btn-color;
    color: #ffffff;
  }
  .canel {
    background-color: #ffffff;
    color: $primary-btn-color;
    // border: 1px solid $primary-btn-color;
  }
  .complete {
    background-color: #ffffff;
    color: $primary-btn-color;
    border: 1px solid $primary-btn-color;
  }
}
.u-loading-icon {
  margin: 8px 0;
}
</style>
